package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.ClazzsMapper;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Clazzs;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBody;
import com.itheima.service.ClazzsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzsServiceImpl implements ClazzsService {
    @Autowired
    private ClazzsMapper clazzsMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public PageBody findClazzsByPage(String name, String begin, String end, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Clazzs> list = clazzsMapper.findAllByPage(name, begin, end);
        System.out.println(list);
        PageInfo<Clazzs> pageInfo =  new PageInfo<>(list);
        return new PageBody(pageInfo.getTotal(),pageInfo.getList().toArray());
    }

    @Override
    public List<Clazzs> findAll() {
        return clazzsMapper.findAll();
    }

    @Override
    public void saveClazzs(Clazzs clazzs) {
        LocalDate beginDate = clazzs.getBeginDate();
        // 根据开班事件推算开班状态
        clazzs.setStatus(beginDate.isBefore(LocalDate.now()) ? "进行中" : "未开始");
        clazzs.setCreateTime(LocalDateTime.now());
        clazzs.setUpdateTime(LocalDateTime.now());
        Integer masterId = clazzs.getMasterId();
        Emp empById = employeeMapper.findEmpById(masterId);
        clazzs.setMasterName(empById.getName());
        clazzsMapper.saveClazzs(clazzs);
    }

    @Override
    public Clazzs findClazzsById(Integer id) {
        Clazzs clazzsById = clazzsMapper.findClazzsById(id);
        return clazzsById;
    }

    @Override
    public void updateClazzsById(Clazzs clazzs) {
        LocalDate beginDate = clazzs.getBeginDate();
        clazzs.setStatus(beginDate.isBefore(LocalDate.now()) ? "进行中" : "未开始");
        clazzs.setUpdateTime(LocalDateTime.now());
        clazzsMapper.updateClazzById(clazzs);
    }

    @Override
    public void deleteById(Integer id) {
        clazzsMapper.deleteById(id);
    }
}
